package com.zr.controller;

import com.zr.common.download.ZipUtils;
import com.zr.dto.file.StaffFileRequest;
import com.zr.entity.StaffFile;
import com.zr.pojo.Result;
import com.zr.service.StaffFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipOutputStream;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/staffFile")
public class StaffFileController {

    @Autowired
    private StaffFileService staffFileService;

    /**
     * 压缩文件
     * @param staffFileRequest
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/downloadFiles")
    public Result downloadFiles(@RequestBody StaffFileRequest staffFileRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ids = staffFileRequest.getIds();
        List<StaffFile> StaffFileList = new ArrayList<StaffFile>();
        if(!StringUtils.isEmpty(ids)){
            String[] idss = ids.split(",");
            if(idss != null && idss.length > 0){
                List<String> filePaths = new ArrayList<String>();
                for (String id: idss) {
                    StaffFile dbFile = staffFileService.queryFileByteArray(Integer.valueOf(id));
                    StaffFileList.add(dbFile);
                }
            }
        }
        String zipName = "myfile.zip";
        response.setContentType("APPLICATION/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            for (Iterator<StaffFile> it = StaffFileList.iterator(); it.hasNext(); ) {
                StaffFile file = it.next();
                ZipUtils.doCompress(file.getFileUrl(), out);
                response.flushBuffer();
            }
        } catch (Exception e) {
            log.error("下载异常：{}",e.getMessage());
            return Result.serviceFail("文件下载失败");
        } finally {
            out.close();
        }
        return null;
    }
}
